import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:fluwx/fluwx.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../../../network/http_config.dart';
import '../../../theme/theme_color.dart';
import '../../../utils/loading.dart';
import '../../../utils/provider.dart';

class ShopPromoteCodePage extends StatefulWidget {
  Map<String, dynamic>? resMap;

  ShopPromoteCodePage({Key? key, this.resMap}) : super(key: key);

  @override
  State<ShopPromoteCodePage> createState() => ShopPromoteCodePageState();
}

class ShopPromoteCodePageState extends State<ShopPromoteCodePage> {
  String _inviteCode = "";
  String _profileNo = "";
  List<GlobalKey> rootKeyList = [
    GlobalKey(),
    GlobalKey(),
    GlobalKey(),
    GlobalKey(),
    GlobalKey(),
    GlobalKey(),
  ];
  int currentRootKey = 0;

  @override
  void initState() {
    super.initState();
    _inviteCode = widget.resMap?['shareCode'];
    _profileNo = widget.resMap?['profileNo'];
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
        appBar: AppBar(
          title: Text(
            "推广码",
            style: TextStyle(
              color: ThemeColor.textColor,
              fontSize: 16,
            ),
          ),
          elevation: 0,
          backgroundColor: const Color.fromRGBO(113, 89, 245, 0.14),
        ),
        backgroundColor: const Color.fromRGBO(236, 236, 236, 1),
        body: SingleChildScrollView(
          child: GestureDetector(
            onLongPress: () {
              // _globalKey.currentContext as cu;
              _capturePng();
            },
            child: Column(
              children: [buildBanner(size), _bottomItem(size)],
            ),
          ),
        )
        // buildContent(),
        );
  }

  Widget buildBanner(final size) {
    List<String> imgList = [
      "images/ic_invite1.png",
      "images/ic_invite2.png",
      "images/ic_invite3.png",
      "images/ic_invite4.png",
      "images/ic_invite5.png",
      "images/ic_invite6.png",
    ];

    return Container(
      padding: const EdgeInsets.fromLTRB(18, 5, 20, 0),
      color: const Color.fromRGBO(113, 89, 245, 0.14),
      child: AspectRatio(
        //设置图片的展示比例之后，可以不设置外层的宽度，或者设置成infinity630 / 924
        aspectRatio: 630 / 924,
        child: Swiper(
          itemCount: imgList.length,
          itemBuilder: (BuildContext context, int index) {
            currentRootKey = index;

            return RepaintBoundary(
              key: rootKeyList[index],
              child: Stack(
                children: [
                  Center(
                    child: Container(
                        color: Colors.white,
                        child: ClipRRect(
                          child: Image.asset(
                            imgList[index],
                            fit: BoxFit.fill,
                          ),
                        )),
                  ),
                  Center(
                    child: Container(
                      width: 150,
                      height: 154,
                      margin: const EdgeInsets.only(
                        top: 250,
                      ),
                      color: Colors.white,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const SizedBox(
                            height: 10,
                          ),
                          Text(
                            '都肆商圈ID：' + _profileNo,
                            style: const TextStyle(
                                fontSize: 11, color: Color(0xFF401C66)),
                          ),
                          // const SizedBox(height: 5,),
                          QrImageView(
                            padding: const EdgeInsets.all(3),
                            backgroundColor: Colors.white,
                            data: _getQrInfo(),
                            version: QrVersions.auto,
                            size: 114,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
          //分页指示器
          pagination: _buildSwiperPagination(),

          //页面上的左右箭头
          control: SwiperControl(
            color: ThemeColor.appColor,
            size: 20,
          ),
          //自动轮播
          autoplay: false,
          loop: true,
        ),
      ),
    );
  }

  _buildSwiperPagination() {
    // 分页指示器
    return SwiperPagination(
      //指示器显示的位置 Alignment.bottomCenter 底部中间
      alignment: Alignment.bottomCenter,
      // 距离调整
      margin: const EdgeInsets.all(0),
      // 指示器构建
      builder: DotSwiperPaginationBuilder(
          // 点之间的间隔
          space: 3,
          // 没选中时的大小
          size: 8,
          // 选中时的大小
          activeSize: 8,
          // 没选中时的颜色
          color: ThemeColor.checkNormalColor,
          //选中时的颜色
          activeColor: ThemeColor.appColor),
    );
  }

  Widget _bottomItem(final size) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          color: const Color.fromRGBO(113, 89, 245, 0.14),
          margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
          //
          child: Container(
            margin: const EdgeInsets.fromLTRB(60, 20, 60, 0),
            padding: const EdgeInsets.symmetric(vertical: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(child: Container()),
                InkWell(
                  onTap: () {
                    _onClick('wechat', _getQrInfo());
                  },
                  child: _buildIconText("images/ic_wechatfriend.png", ""),
                ),
                const SizedBox(
                  width: 60,
                ),
                InkWell(
                  onTap: () {
                    _onClick('circle', _getQrInfo());
                  },
                  child: _buildIconText("images/ic_friendCicle.png", ""),
                ),
                Expanded(child: Container()),
              ],
            ),
          ),
        ),

        // const SizedBox(height: 20,),
        Container(
            // color: Colors.red,
            color: const Color.fromRGBO(113, 89, 245, 0.14),
            margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
            width: MediaQuery.of(context).size.width,
            height: 130,
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  margin: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  height: 45,
                  width: size.width - 80,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(22.5)),
                    color: const Color(0xFF7F69D9),
                  ),
                  child: const Text(
                    '长按图片下载图片',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 5),
                  child: Text(
                    '邀请好友增加20次机会',
                    style: TextStyle(
                        color: ThemeColor.textColorSecond, fontSize: 14),
                  ),
                ),
              ],
            )),
      ],
    );
  }

  Widget _buildIconText(String icon, String text) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Image.asset(icon, width: 45, height: 70),
      ],
    );
  }

  String _getQrInfo() {
    print('xxxx   ${HttpConfig.baseUrl}?invite_code=$_inviteCode');
    return _inviteCode.isEmpty
        ? ""
        : HttpConfig.baseUrl + "?invite_code=$_inviteCode";
  }

  Future<Uint8List?> _capturePng() async {
    try {
      RenderRepaintBoundary boundary = rootKeyList[currentRootKey]
          .currentContext!
          .findRenderObject() as RenderRepaintBoundary;
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List? pngBytes = byteData?.buffer.asUint8List();
      if (pngBytes != null) {
        final res = await ImageGallerySaver.saveImage(pngBytes);
        if (res == null || res == '') {
          toast("保存失败");
        } else {
          toast("保存到相册成功");
        }
      }
      return pngBytes; //这个对象就是图片数据
    } catch (e) {
      print('=============');
      print(e);
    }
    return null;
  }
}

void requestPermission(Permission permission) async {
  //发起权限申请
  PermissionStatus status = await permission.request();
  // 返回权限申请的状态 status
  print('权限状态$status');
  if (status.isPermanentlyDenied) {
    openAppSettings();
  }
}

_onClick(String id, String Qr) {
  switch (id) {
    case 'wechat':
      {
        //个人设置
        String asset = 'images/ic_inviteLogo.png';
        String asset1 = Provider.nickName;
        print(asset1);
        var model = WeChatShareWebPageModel(
          Qr,
          title: '偶然遇见另一半',
          scene: WeChatScene.SESSION,
          description: '<$asset1>\n邀请您参加偶然遇见、寻找您心仪的另一半，开启您的幸福之旅！',
          thumbnail: WeChatImage.asset(asset, suffix: 'png'),
        );

        shareToWeChat(model);
        break;
      }
    case 'circle':
      {
        String asset = 'images/ic_inviteLogo.png';
        var model = WeChatShareWebPageModel(
          Qr,
          title: '偶然遇见另一半',
          scene: WeChatScene.TIMELINE,
          description: '<${Provider.nickName}>\n邀请您参加偶然遇见、寻找您心仪的另一半，开启您的幸福之旅！',
          mediaTagName: 'dd',
          thumbnail: WeChatImage.asset(asset, suffix: 'png'),
        );

        shareToWeChat(model);
        break;
      }
  }
}
